package com.rongshu.view.userInfo.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.DataCleanManager;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.penpal.view.ShareDialogListener;
import com.rongshu.view.userInfo.entity.ThirdPartyInfo;
import com.rongshu.view.userInfo.iview.SettingView;
import com.rongshu.view.userInfo.presenter.SettingPresenter;
import com.rongshu.widget.BanyanDialog;
import com.rongshu.widget.ShareBottomDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.utils.ApkUtils;
import com.widget.toast.ToastUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class SettingActivity extends BaseActivity<SettingPresenter> implements SettingView {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;//标题
    @BindView(R.id.txtTel)
    TextView txtTel;
    @BindView(R.id.txt_cache)
    TextView txt_cache;
    @BindView(R.id.iv_binding_qq)
    ImageView iv_binding_qq;
    @BindView(R.id.iv_binding_xinlang)
    ImageView iv_binding_xinlang;
    @BindView(R.id.iv_binding_weixin)
    ImageView iv_binding_weixin;
    @BindView(R.id.txt_version)
    TextView versionCode;

    //phone
    private String phone = null;
    //request
    private final int MODIFY_PASSWORD_REQUEST_CODE = 0x01;//修改密码界面
    private final int BIND_PHONE_REQUEST_CODE = 0x02;//绑定手机号
    private final int CHANGE_PHONE_REQUEST_CODE = 0x03;//更换手机号
    private BanyanDialog dialog = null;
    //intent
    private Intent intent = null;
    //map
    private Map<String, Object> map = null;
    //boolean
    private boolean isBoundQQ = false, isBoundWX = false, isBoundXL;

    @Override
    protected int initLayout() {
        return R.layout.activity_setting_view;
    }

    @Override
    protected void initView() {
        //set presenter
        setPresenter(new SettingPresenter(this), this);
        //获取意图数据
        intent = getIntent();
        phone = intent.getStringExtra(Constant.INTENT_DATA);
        //设置title
        txt_top_title.setText(R.string.setting);
        //手机号
        txtTel.setText(phone);
        //缓存
        try {
            txt_cache.setText(DataCleanManager.getTotalCacheSize(getApplicationContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //version
        versionCode.setText("V" + ApkUtils.versionName(this));
    }


    @Override
    protected void initData() {
    }

    @Override
    protected void updateViews(boolean isRefresh) {
        refreshView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getThirdParty();
    }

    /**
     * 更新view
     */
    private void refreshView() {
        iv_binding_weixin.setImageResource(isBoundWX ? R.drawable.bound_weixin_green_icon : R.drawable.bound_weixin_gray_icon);
        iv_binding_xinlang.setImageResource(isBoundXL ? R.drawable.bound_xinlang_red_icon : R.drawable.bound_xinlang_gray_icon);
        iv_binding_qq.setImageResource(isBoundQQ ? R.drawable.bound_qq_blue_icon : R.drawable.bound_qq_gray_icon);
    }

    /**
     * 退出登录
     */
    private void LoginOut() {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getLogOut(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取第三方账号绑定信息和实名认证信息
     */
    private void getThirdParty() {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getThirdParty(user_id, Common.encryptionSign(map));
        map.clear();
    }

    @OnClick({R.id.layout_back, R.id.layout_setting_password, R.id.layout_phone, R.id.layout_third_binding,
            R.id.layout_real_authentication, R.id.layout_privacy, R.id.layout_push_notification,
            R.id.layout_recommend_to_friends, R.id.layout_clean_cache, R.id.layout_about_us,
            R.id.txt_exit, R.id.layout_person_info})
    public void onClick(View view) {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_person_info://个人信息
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                intent = new Intent(SettingActivity.this, PerfectInfomationActivity.class);
                intent.putExtra(Constant.INTENT_DATA, user_id);
                startActivity(intent);
                break;
            case R.id.layout_setting_password://设置密码
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    intent = new Intent(SettingActivity.this, BindPhoneActivity.class);
                    intent.putExtra(Constant.INTENT_TYPE, Constant.BIND_PHONE);
                    startActivityForResult(intent, BIND_PHONE_REQUEST_CODE);
                } else {
                    intent = new Intent(SettingActivity.this, ModifyPasswordActivity.class);
                    intent.putExtra(Constant.INTENT_TYPE, Constant.CHANGE_PWD);
                    intent.putExtra(Constant.INTENT_DATA, phone);
                    startActivityForResult(intent, MODIFY_PASSWORD_REQUEST_CODE);
                }
                break;
            case R.id.layout_phone://手机号
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    intent = new Intent(SettingActivity.this, BindPhoneActivity.class);
                    intent.putExtra(Constant.INTENT_TYPE, Constant.BIND_PHONE);
                    startActivityForResult(intent, BIND_PHONE_REQUEST_CODE);
                } else {
                    final BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
                    builder.setTitle(getString(R.string.hint))
                            .setContent(getString(R.string.whether_change_phone))
                            .setLeft(getString(R.string.cancle))
                            .setRight(getString(R.string.change))
                            .setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
                                @Override
                                public void leftClickListener() {
                                    dialog.dismiss();
                                }

                                @Override
                                public void rightClickListener() {
                                    dialog.dismiss();
                                    intent = new Intent(SettingActivity.this, ModifyPasswordActivity.class);
                                    intent.putExtra(Constant.INTENT_TYPE, Constant.CHANGE_PHONE);
                                    intent.putExtra(Constant.INTENT_DATA, phone);
                                    startActivityForResult(intent, CHANGE_PHONE_REQUEST_CODE);
                                }
                            });
                    dialog = builder.create();
                    dialog.show();
                }
                break;
            case R.id.layout_third_binding://第三方账户绑定
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                intent = new Intent(this, ThirdBindingActivity.class);
                intent.putExtra(Constant.INTENT_MESSAGE, phone);
                startActivity(intent);
                break;
            case R.id.layout_real_authentication://实名认证
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                intent = new Intent(this, RealAuthenticationActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_privacy://隐私设置
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                intent = new Intent(this, PrivacySettingsAcitivity.class);
                startActivity(intent);
                break;
            case R.id.layout_push_notification://消息推送
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                intent = new Intent(this, PushNotificationActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_recommend_to_friends://推荐给好友
                shareToFriend();
                break;
            case R.id.layout_about_us://关于我们
                intent = new Intent(this, AboutUsAcitivity.class);
                startActivity(intent);
                break;
            case R.id.layout_clean_cache: //清理缓存
                try {
                    DataCleanManager.clearAllCache(getApplicationContext());
                    txt_cache.setText(DataCleanManager.getTotalCacheSize(getApplicationContext()));
                    toast("清理成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.txt_exit://退出
                if (user_id == 0) {
                    LoginUtils.toLogin(this);
                    return;
                }
                showExitDialog();
                break;
        }
    }


    /**
     * 彻底删除dialog
     */
    private void showExitDialog() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("退出当前账号")
                .setContent("确定要退出当前账号吗？")
                .setLeft("取消")
                .setRight("确认");
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                LoginOut();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void shareToFriend() {
        ShareBottomDialog.Builder builder = new ShareBottomDialog.Builder(this);
        builder.setSharePositionListener(new ShareDialogListener() {
            @Override
            public void onShareClick(DialogInterface dialog, SHARE_MEDIA position) {
                dialog.dismiss();
                requestShare(position);
            }
        });
        builder.create().show();
    }

    private void requestShare(SHARE_MEDIA type) {
        final UMWeb web = new UMWeb("http://www.52rongshu.com/");
        web.setTitle("一款挺文艺的阅读软件");//标题
        web.setThumb(new UMImage(this, R.drawable.icon));  //缩略图
        web.setDescription("榕书是一款将阅读写作分享交流于一体的的APP");//描述
        new ShareAction(this)
                .setPlatform(type)//传入平台
                .withMedia(web)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        ToastUtils.show(throwable.getMessage());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        ToastUtils.show("分享取消");
                    }
                })
                .share();
    }

    /**
     * 退出登陆
     */
    private void exit() {
        //清楚数据
        UserInfoUtils.removeUserInfo();
        finish();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String tel = "";
            if (data != null && data.hasExtra(Constant.INTENT_DATA)) {
                tel = data.getStringExtra(Constant.INTENT_DATA);
            }
            switch (requestCode) {
                case MODIFY_PASSWORD_REQUEST_CODE://修改密码
                    showSuccessDialog(getString(R.string.save_success));
                    break;
                case BIND_PHONE_REQUEST_CODE://绑定手机号
                    if (!TextUtils.isEmpty(tel)) {
                        phone = tel;
                        txtTel.setText(phone);
                    }
                    showSuccessDialog(getString(R.string.binding_success));
                    break;
                case CHANGE_PHONE_REQUEST_CODE://更换手机号
                    if (!TextUtils.isEmpty(tel)) {
                        phone = tel;
                        txtTel.setText(phone);
                    }
                    showSuccessDialog(getString(R.string.change_success));
                    break;
            }
        }
    }

    /**
     * 提交，保存，绑定成功
     */
    public void showSuccessDialog(String content) {
        toast(content);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.dismiss();
            dialog.cancel();
            dialog = null;
        }

    }

    /**
     * 退出登录回调
     *
     * @param bean
     */
    @Override
    public void onExit(INetBean bean) {
        if (bean.getErrCode() == 0) {
            exit();
        } else {
            toast(bean.getErrMsg());
        }
    }

    @Override
    public void onThirdPartyInfo(ThirdPartyInfo info) {
        if (info.getErrCode() == 0) {
            ThirdPartyInfo.ResponseBean responseBean = info.getResponse();
            if (responseBean != null) {
                //bound_qq_gray_icon
                isBoundQQ = TextUtils.isEmpty(responseBean.getQq()) ? false : true;
                //bound_weixin_gray_icon
                isBoundWX = TextUtils.isEmpty(responseBean.getWechat()) ? false : true;
                //xinlang
                isBoundXL = TextUtils.isEmpty(responseBean.getWeibo()) ? false : true;
                refreshView();
            }
        } else {
            toast(info.getErrMsg());
        }
    }
}
